package com.open.capacity.user.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.open.capacity.common.model.TitleType;
import com.open.capacity.common.util.PageUtil;
import com.open.capacity.common.web.PageResult;
import com.open.capacity.common.web.Result;
import com.open.capacity.user.dao.TitleTypeDao;
import com.open.capacity.user.service.TitleTypeService;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @author liutao
 * @date 2021-02-01 19:07
 */
@Service
public class TitleTypeServiceImpl implements TitleTypeService {

    @Autowired
    private TitleTypeDao titleTypeDao;

    // 模糊查询称号类型
    @Override
    public PageResult getSelectTitleTypes(Map<String, Object> params) {
        if (MapUtils.getInteger(params, "page")!=null && MapUtils.getInteger(params, "limit")!=null){
            PageHelper.startPage(MapUtils.getInteger(params, "page"),MapUtils.getInteger(params, "limit"),true);
        }
//        PageUtil.pageParamConver(params,true);
        List<TitleType> titleTypes = titleTypeDao.getSelectTitleTypes(params);
        PageInfo<TitleType> pageInfo = new PageInfo<>(titleTypes);
        return PageResult.<TitleType>builder().code(0).
                data(pageInfo.getList()).count(pageInfo.getTotal()).build();
    }

    // 添加称号类型
    @Override
    public Result addTitleType(TitleType titleType) {
        boolean isHave = isHaveTitleType(titleType.getTpname(),null);
        if (!isHave){
            int result = titleTypeDao.addTitleType(titleType);
            return Result.succeed(result == 1?"添加成功":"添加失败");
        }
        return Result.failed("该称号类型已存在");
    }

    // 修改称号类型
    @Override
    public Result updateTitleType(TitleType titleType) {
        boolean isHave = isHaveTitleType(titleType.getTpname(),titleType.getTttpid());
        if (isHave){
            return Result.failed("该称号类型已存在");
        }
        int result = titleTypeDao.updateTitleType(titleType);
        return Result.succeed(result == 1 ? "修改成功" : "修改失败");
    }

    // 删除称号类型
    @Override
    public Result delTitleType(int tttpid) {
        int result = titleTypeDao.delTitleType(tttpid);
        return Result.succeed(result > 0?"删除成功":"删除失败");
    }

    // 判断称号类型是否存在
    private boolean isHaveTitleType(String tpname, Integer tttpid) {
        Integer isHave = titleTypeDao.isHaveTitleType(tpname,tttpid);
        return isHave > 0;
    }

}
